<template>
  <view class="chat-messages-wrapper">
    <scroll-view 
      class="chat-messages-component" 
      scroll-y="true" 
      bounce="false"
      :scroll-into-view="internalScrollToView"
      @scrolltoupper="$emit('load-more')"
      @scroll="handleScroll"
      :style="{ paddingTop: contentPadding.top, paddingBottom: contentPadding.bottom }"
    >
      <view id="chat-list">
        <!-- 消息列表 -->
        <block v-for="(message, index) in messages" :key="index" :id="'msg-' + index">
          <!-- AI消息 -->
          <view class="message ai-message" v-if="message.sender === 'bot'">
            <view class="message-content">
              <!-- 根据消息类型渲染不同内容 -->
              <view class="message-bubble" v-if="message.type === 'text' && message.status !== 'loading' && message.status !== 'error'">
                <rich-text :nodes="formatMessageContent(message.content)"></rich-text>
              </view>
              <view class="message-bubble loading" v-else-if="message.status === 'loading'">
                <view class="loading-spinner"></view>
                <text class="loading-text"> <span class="thinking-dots"></span></text>
              </view>
              <view class="message-bubble error" v-else-if="message.status === 'error'">
                <view class="error-icon">⚠️</view>
                <text class="error-text">{{ message.content }}</text>
                <view class="retry-button" v-if="message.canRetry" @tap="$emit('retry-message', message)">
                  <text class="retry-text">重试</text>
                </view>
              </view>
              <view class="message-bubble image-message" v-else-if="message.type === 'image'">
                <image :src="message.content.imageUrl" mode="widthFix" class="message-image"></image>
                <view class="image-text" v-if="message.content.text">{{ message.content.text }}</view>
              </view>
              <view class="message-bubble voice-message" v-else-if="message.type === 'voice'" @tap="$emit('play-voice', message)">
                <view class="voice-icon">
                  <image src="/static/images/doubao_icon/voice_play.png" mode="aspectFit"></image>
                </view>
                <view class="voice-duration">{{ message.content.duration }}''</view>
              </view>
              
              <!-- 消息操作按钮 - 仅在最后一条AI消息显示且非加载中非错误状态 -->
              <view class="message-actions" v-if="index === messages.length - 1 && message.sender === 'bot' && message.status !== 'loading' && message.status !== 'error'">
                <view class="action-button" @tap="$emit('copy-message', message)">
                  <image src="/static/images/doubao_icon/copy.png" mode="aspectFit" class="action-icon-img"></image>
                </view>
                <view class="action-button" @tap="$emit('play-tts', message.id)">
                  <!-- 根据合成状态显示不同图标 -->
                  <view v-if="isSynthesizing && synthesizingMessageId === message.id" class="tts-loading-spinner"></view>
                  <image v-else src="/static/images/doubao_icon/voice2.png" mode="aspectFit" class="action-icon-img"></image>
                </view>
                <view class="action-button" @tap="$emit('favorite-message', message)">
                  <image src="/static/images/doubao_icon/like.png" mode="aspectFit" class="action-icon-img"></image>
                </view>
                <view class="action-button" @tap="$emit('share-message', message)">
                  <image src="/static/images/doubao_icon/share.png" mode="aspectFit" class="action-icon-img"></image>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 用户消息 -->
          <view class="message user-message" v-else>
            <view class="message-content">
              <!-- 根据消息类型渲染不同内容 -->
              <view class="message-bubble" v-if="message.type === 'text' && message.status !== 'loading'">
                <rich-text :nodes="formatMessageContent(message.content)"></rich-text>
              </view>
              <view class="message-bubble loading" v-else-if="message.status === 'loading'">
                <view class="loading-spinner"></view>
                <text class="loading-text">正在思考中<span class="thinking-dots"></span></text>
              </view>
              <view class="message-bubble image-message" v-else-if="message.type === 'image'">
                <image :src="message.content.imageUrl" mode="widthFix" class="message-image"></image>
                <view class="image-text" v-if="message.content.text">{{ message.content.text }}</view>
              </view>
              <view class="message-bubble voice-message" v-else-if="message.type === 'voice'" @tap="$emit('play-voice', message)">
                <view class="voice-icon">
                  <image src="/static/images/doubao_icon/voice_play.png" mode="aspectFit"></image>
                </view>
                <view class="voice-duration">{{ message.content.duration }}''</view>
              </view>
            </view>
          </view>
        </block>
      </view>
    </scroll-view>
    
    <!-- 滚动到底部悬浮按钮 -->
    <view class="scroll-to-bottom-button" v-if="showScrollButton" @tap="scrollToBottom">
      <image src="/static/images/doubao_icon/bottom.png" mode="aspectFit" class="bottom-button-icon"></image>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ChatMessages',
  props: {
    messages: {
      type: Array,
      required: true
    },
    scrollToView: {
      type: String,
      default: ''
    },
    contentPadding: {
      type: Object,
      default: () => ({ top: '80px', bottom: '90px' })
    },
    isSynthesizing: {
      type: Boolean,
      default: false
    },
    synthesizingMessageId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showScrollButton: false, // 默认隐藏滚动按钮
      internalScrollToView: '', // 添加内部使用的scrollToView状态
      scrollTop: 0, // 当前滚动位置
      scrollHeight: 0, // 滚动区域总高度
      scrollThreshold: 100 // 滚动阈值，超过此值才显示按钮，调小一些更灵敏
    };
  },
  watch: {
    // 监听外部传入的scrollToView变化
    scrollToView: {
      immediate: true,
      handler(val) {
        this.internalScrollToView = val;
      }
    },
    // 监听消息数组变化，自动滚动到底部
    messages: {
      handler(newVal, oldVal) {
        if (newVal.length > oldVal.length) {
          // 新消息添加时，滚动到底部
          this.scrollToBottom();
          // 隐藏滚动按钮，因为已经在底部了
          this.showScrollButton = false;
        }
      },
      deep: true
    }
  },
  methods: {
    // 处理特殊格式
    formatMessageContent(content) {
      if (typeof content !== 'string') {
        return content;
      }
      
      // 在uni-app中，rich-text支持两种形式：HTML字符串或nodes数组
      // 这里我们选择返回HTML字符串
      
      // 处理 ### 为换行符
      let formattedContent = content.replace(/###/g, '<br>');
      
      // 处理 **文本** 为加粗/小标题
      formattedContent = formattedContent.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 如果已经是HTML格式，直接返回
      if (formattedContent.indexOf('<') !== -1 && formattedContent.indexOf('>') !== -1) {
        return formattedContent;
      }
      
      // 否则包裹在p标签中
      return '<p>' + formattedContent + '</p>';
    },
    
    // 滚动到底部
    scrollToBottom() {
      // 设置scrollToView为最后一条消息的ID
      if (this.messages.length > 0) {
        this.internalScrollToView = 'msg-' + (this.messages.length - 1);
        
        // 使用nextTick确保DOM已更新
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this);
          query.select('.chat-messages-component').boundingClientRect(data => {
            if (data) {
              const scrollView = uni.createSelectorQuery().in(this).select('.chat-messages-component');
              scrollView.scrollOffset(res => {
                uni.pageScrollTo({
                  scrollTop: res.scrollHeight,
                  duration: 300
                });
              }).exec();
            }
          }).exec();
          
          // 已滚动到底部，隐藏按钮
          this.showScrollButton = false;
        });
      }
    },
    
    // 处理滚动事件
    handleScroll(e) {
      // 获取当前滚动位置和区域信息
      const scrollTop = e.detail.scrollTop; // 当前滚动位置
      const scrollHeight = e.detail.scrollHeight; // 内容总高度
      
      // 需要获取可视区域高度，但uni-app在某些平台可能无法直接通过事件获取
      // 尝试通过查询节点获取可视区域高度
      const query = uni.createSelectorQuery().in(this);
      query.select('.chat-messages-component').boundingClientRect(rect => {
        if (rect) {
          const visibleHeight = rect.height; // 可视区域高度
          
          // 计算距离底部的距离
          const distanceFromBottom = scrollHeight - scrollTop - visibleHeight;
          
          // 更新状态
          this.scrollTop = scrollTop;
          this.scrollHeight = scrollHeight;
          
          console.log(`Scroll info - Top: ${scrollTop}, Height: ${scrollHeight}, Visible: ${visibleHeight}, Distance: ${distanceFromBottom}`);
          
          // 如果用户已经上滑超过阈值距离，显示回到底部按钮
          if (distanceFromBottom > this.scrollThreshold) {
            this.showScrollButton = true;
          } else {
            // 如果在底部附近，隐藏按钮
            this.showScrollButton = false;
          }
        }
      }).exec();
    }
  },
  mounted() {
    // 组件挂载时滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  }
}
</script>

<style lang="scss" scoped>
.chat-messages-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  flex: 1;
}

.chat-messages-component {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden; // 禁止水平滚动
  -webkit-overflow-scrolling: touch;
  width: 100%;

  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
  }
}

.scroll-view-content {
  display: flex;
  flex-direction: column;
  padding: 30px;
  box-sizing: border-box;
}

.message {
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
  &:first-child {
    margin-top: 5px; /* 确保第一条消息有足够的顶部间距 */
  }
}

.ai-message {
  justify-content: flex-start;
  padding-left: 0;
  
  .message-content {
    max-width: 92%;
    margin-left: 0px;
    
    .message-bubble {
      background-color: #ffffff;
      color: #333;
      padding: 15px;
      border-radius: 12px 12px 12px 12px;
      font-size: 15px;
      line-height: 1.5;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
      
      :deep(strong) {
        display: block;
        font-weight: bold;
        margin: 5px 0;
        font-size: 16px;
        color: #333;
      }
      
      :deep(br) {
        display: block;
        content: "";
        margin-top: 8px;
      }
      
      :deep(p) {
        margin: 0;
        padding: 0;
      }
    }
    
    .image-message {
      padding: 8px;
      
      .message-image {
        width: 100%;
        max-width: 200px;
        border-radius: 4px;
        margin-bottom: 4px;
      }
      
      .image-text {
        margin-top: 6px;
        font-size: 14px;
      }
    }
    
    .voice-message {
      display: flex;
      align-items: center;
      min-width: 60px;
      
      .voice-icon {
        width: 18px;
        height: 18px;
        margin-right: 8px;
        
        image {
          width: 100%;
          height: 100%;
        }
      }
      
      .voice-duration {
        color: #666;
        font-size: 14px;
      }
    }
    
    // 消息操作按钮样式
    .message-actions {
      display: flex;
      margin-top: 12px;
      justify-content: flex-start;
      
      .action-button {
        width: 32px;
        height: 32px;
        background-color: #f5f5f5;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;
        
        .action-icon-img {
          width: 18px;
          height: 18px;
        }
        
        // TTS加载动画
        .tts-loading-spinner {
          width: 18px;
          height: 18px;
          border: 2px solid rgba(0, 120, 255, 0.2);
          border-top: 2px solid #0078ff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
        
        &:active {
          background-color: #e0e0e0;
          transform: scale(0.95);
        }
      }
    }
  }
}

.user-message {
  justify-content: flex-end;
  padding-right: 0;
  
  .message-content {
    max-width: 75%;
    margin-right: 16px;
    
    .message-bubble {
      background-color: #0078ff;
      color: #ffffff;
      padding: 15px;
      border-radius: 12px 4px 12px 12px;
      font-size: 15px;
      line-height: 1.5;
      word-break: break-word;
      margin-right: 15px;
      
      :deep(strong) {
        display: block;
        font-weight: bold;
        margin: 5px 0;
        font-size: 16px;
        color: #ffffff;
      }
      
      :deep(br) {
        display: block;
        content: "";
        margin-top: 8px;
      }
      
      :deep(p) {
        margin: 0;
        padding: 0;
      }
    }
    
    .image-message {
      padding: 8px;
      
      .message-image {
        width: 100%;
        max-width: 200px;
        border-radius: 4px;
        margin-bottom: 4px;
      }
      
      .image-text {
        margin-top: 6px;
        font-size: 14px;
        color: #eee;
      }
    }
    
    .voice-message {
      display: flex;
      align-items: center;
      min-width: 60px;
      
      .voice-icon {
        width: 18px;
        height: 18px;
        margin-right: 8px;
        
        image {
          width: 100%;
          height: 100%;
          filter: brightness(5);
        }
      }
      
      .voice-duration {
        color: #ffffff;
        font-size: 14px;
      }
    }
  }
}

/* --- 从 doubao_chat.vue 迁移的加载样式 --- */

// 添加思考中的动画样式
.thinking-dots {
  display: inline-block;
  &::after {
    content: '';
    animation: thinking 1.5s infinite;
  }
}

@keyframes thinking {
  0% { content: '.'; }
  33% { content: '..'; }
  66% { content: '...'; }
  100% { content: '.'; }
}

// 加载状态的消息样式
.message-bubble.loading {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #ffffff;
  border-radius: 4px 12px 12px 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .loading-spinner {
    width: 16px;
    height: 16px;
    margin-right: 5px;
    border: 2px solid rgba(0, 120, 255, 0.2);
    border-top: 2px solid #0078ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text {
    font-size: 15px;
    color: #666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 错误消息样式
.message-bubble.error {
  display: flex;
  flex-direction: column;
  padding: 12px 16px;
  background-color: #fff0f0;
  border-radius: 12px 12px 12px 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #ff4d4f;

  .error-icon {
    font-size: 18px;
    margin-bottom: 8px;
  }
  
  .error-text {
    font-size: 14px;
    color: #ff4d4f;
    margin-bottom: 12px;
    line-height: 1.5;
  }
  
  .retry-button {
    align-self: flex-end;
    background-color: #ff4d4f;
    color: white;
    padding: 6px 12px;
    border-radius: 16px;
    font-size: 14px;
    
    &:active {
      opacity: 0.8;
    }
    
    .retry-text {
      color: white;
    }
  }
}

// 滚动到底部按钮样式
.scroll-to-bottom-button {
  position: fixed;
  bottom: 260px; /* 调整位置，使其位于偏下的位置 */
  right: 20px;
  width: 46px;
  height: 46px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.15);
  z-index: 999; /* 确保按钮位于最上层 */
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    background-color: rgba(240, 240, 240, 0.9);
  }
  
  .bottom-button-icon {
    width: 26px;
    height: 26px;
  }
}
</style> 